package controllers

import (
	"day01/models/mysql"
	"day01/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

func UserLogin(c *gin.Context) {

	var user mysql.User
	userName := c.PostForm("user_name")
	password := c.PostForm("password")
	mysql.DB.Where("user_name = ?", userName).Limit(1).Find(&user)
	if user.ID == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"message": "用户不存在",
		})
		return
	}
	if user.Password != password {
		c.JSON(http.StatusBadRequest, gin.H{
			"message": "密码错误",
		})
		return
	}
	handler, _ := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	c.JSON(http.StatusOK, gin.H{
		"message": "登录成功",
		"userId":  user.ID,
		"handler": handler,
	})
}
